package com.cdtu.comon;

import com.cdtu.entity.Study;
import com.cdtu.service.StudyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UseEnableScheduling {
    @Autowired
    StudyService studyService;

    @Value("${reggie.pathVideo}")
    private String basePath;

    @Value("${reggie.pathItem}")
    private String ItemPath;

    @Scheduled(cron = "0 0 3 ? * WED")   //定时器定义，设置执行时间每周3 凌晨3点
    private void process() {
        deleteVideoFile();
        deleteItemFile();
    }

    public void deleteVideoFile(){
        File file = new File(basePath);
        String[] list = file.list();
        List<String> studyVideoSrc = new ArrayList<>();
        List<String> temp=new ArrayList<>();
        List<Study> studies = studyService.queryAll();
        studyVideoSrc=studies.stream().map(item ->{
            return item.getVedioSrc().substring(item.getVedioSrc().indexOf("=")+1);
        }).collect(Collectors.toList());
        for (String s : list) {
            int i = studyVideoSrc.indexOf(s);
            if (i==-1){
                temp.add(s);
            }
        }
        for (String s : temp) {
            uploadCustomPathFile(basePath+s);
        }
    }
    public void deleteItemFile(){
        File file = new File(ItemPath);
        String[] list = file.list();
        List<String> studyItemSrc = new ArrayList<>();
        List<String> temp=new ArrayList<>();
        List<Study> studies = studyService.queryAll();
        studyItemSrc=studies.stream().map(item ->{
            return item.getTopicSrc().substring(item.getTopicSrc().indexOf("=")+1);
        }).collect(Collectors.toList());
        for (String s : list) {
            int i = studyItemSrc.indexOf(s);
            if (i==-1){
                temp.add(s);
            }
        }
        for (String s : temp) {
            uploadCustomPathFile(basePath+s);
        }
    }
    //文件删除(路径)
    public Boolean uploadCustomPathFile(String path){
        return FileSystemUtils.deleteRecursively(new File(path));
    }
    //文件删除(文件)
    public Boolean uploadCustomPathFile(File file){
        return FileSystemUtils.deleteRecursively(file);
    }
}
